package com.zhouk.ams.wx;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.zhouk.ams.constants.RequestMethod;
import com.zhouk.ams.wx.constants.WxConstants;
import com.zhouk.ams.wx.constants.WxUrl;
import com.zhouk.ams.wx.utils.NetworkHelper;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.*;

/**
 * Create By Zhouke on 2017/09/21
 */
@WebServlet(name = "AccessTokenServlet",
        urlPatterns = "/AccessTokenServlet",
        //loadOnStartup = -1,
        initParams = {
                @WebInitParam(name = "appid", value = "wxf7c7bd93a85717ff"),
                @WebInitParam(name = "secret", value = "985385a7e751f62ef11690b038eb82d4")
        })
public class AccessTokenServlet extends HttpServlet {

 private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void init() throws ServletException {
        super.init();
        logger.info("AccessTokenServlet启动");

        //使用线程池
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("getToken-pool-%d").build();
        ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

        singleThreadPool.execute(() -> {
                    while (true) {
                        try {
                            AccessTokenInfo.accessToken = getAccessToken();
                            //获取成功
                            if (AccessTokenInfo.accessToken != null) {
                                //获取到access_token则休眠5400秒(大约1个半小时)
                                logger.info("AccessToken获取成功：{}", AccessTokenInfo.accessToken.getAccessToken());
                                Thread.sleep(5400 * 1000);
                                //10秒钟获取一次
                                //Thread.sleep(10 * 1000);
                            } else {
                                //获取失败
                                logger.debug("AccessToken获取失败,三秒后重试");
                                //获取的access_token为空 休眠3秒
                                Thread.sleep(3 * 1000);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            logger.error("异常消息：{}，堆栈信息：{}", e.getMessage(), e.getStackTrace());
                            try {
                                //发生异常休眠1秒
                                Thread.sleep(1000 * 10);
                            } catch (Exception e1) {

                            }
                        }
                    }
                }
        );
        singleThreadPool.shutdown();

//        Thread thread = new Thread(new Runnable() {
//            @Override
//            public void run() {
//                while (true) {
//                    try {
//                        AccessTokenInfo.accessToken = getAccessToken(appid, secret);
//                        //获取成功
//                        if (AccessTokenInfo.accessToken != null) {
//                            //获取到access_token 休眠7000秒,大约2个小时左右
//                            logger.info("AccessToken获取成功：{}", AccessTokenInfo.accessToken.getAccessToken());
//                            Thread.sleep(7000 * 1000);
//                            //Thread.sleep(10 * 1000);//10秒钟获取一次
//                        } else {
//                            //获取失败
//                            logger.info("AccessToken获取失败,三秒后重试");
//                            Thread.sleep(3 * 1000); //获取的access_token为空 休眠3秒
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        logger.error("异常消息：{}，堆栈信息：{}", e.getMessage(), e.getStackTrace());
//                        try {
//                            Thread.sleep(1000 * 10); //发生异常休眠1秒
//                        } catch (Exception e1) {
//
//                        }
//                    }
//                }
//            }
//        });
//        thread.setName("getAccessToken");
//        thread.start();

    }

    private AccessToken getAccessToken() throws JSONException {
        NetworkHelper netHelper = new NetworkHelper();

        String url = String.format(WxUrl.ACCESS_TOKEN_URL, WxConstants.APP_ID, WxConstants.SECRET);
        //此请求为https的get请求，返回的数据格式为{"access_token":"ACCESS_TOKEN","expires_in":7200}
        JSONObject result = NetworkHelper.httpRequest(url, RequestMethod.GET, null);
        //请求结果转为JSON对象
        AccessToken token = new AccessToken();
        token.setAccessToken(result.getString("access_token"));
        token.setExpiresIn(result.getInt("expires_in"));
        return token;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
